package com.ibo.htlivecamera.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.ibo.htlivecamera.BuildConfig;
import com.ibo.htlivecamera.MainActivity;
import com.ibo.htlivecamera.R;
import com.ibo.htlivecamera.app.Constants;
import com.ibo.htlivecamera.socket.SimpleClient;
import com.ibo.htlivecamera.socket.SimpleEvent;
import com.ibo.htlivecamera.socket.SimpleListener;
import com.ibo.htlivecamera.socket.SimpleListenerAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

public class SocketService extends Service {

    private SimpleClient simpleClient;

    @Override
    public void onCreate() {
        super.onCreate();

        System.out.println("########   serviceOnCreate!");

        if (simpleClient != null && simpleClient.isConnected()) {
            return;
        }
        initSocket();
    }

    private void initSocket() {
        log("init socket " + Constants.HOST);

        ArrayList<String> supportRate = new ArrayList<>();
        supportRate.add("320*240");
        supportRate.add("640*480");
        supportRate.add("720*480");
        supportRate.add("1280*720");
        simpleClient = new SimpleClient("No Name", supportRate);
        simpleClient.setHostAndPort(Constants.HOST, Constants.SOCKET_PORT);
        simpleClient.addListener(new SimpleListenerAdapter() {
            @Override
            public void onConnect() {
                super.onConnect();
                simpleClient.postEvent(new SimpleEvent(SimpleEvent.VERSION, String.valueOf(BuildConfig.VERSION_CODE)));

                reconnectHandler.removeCallbacks(runnable);
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.CONNECTED));
            }

            @Override
            public void onSetRate(int width, int height) {
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.SET_RATE, width + "*" + height));
            }

            @Override
            public void onCameraRotate(String xyz, int step) {
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.CAMERA_ROTATE, xyz + "," + step));
            }

            @Override
            public void onDisconnect() {
                super.onDisconnect();
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.DISCONNECTED));
                startReconnetct();
            }

            @Override
            public void onVolume(int step) {
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.VOLUME, step + ""));
            }

            @Override
            public void onCameraZoom(int step) {
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.CAMERA_ZOOM, step + ""));
            }

            @Override
            public void onRestartSelf() {
                super.onRestartSelf();
            }

            @Override
            public void onSetName(String name) {
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.SET_NAME, name));
            }

            @Override
            public void onStartPush(String url) {
                super.onStartPush(url);
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.START_PUSH, url));
            }

            @Override
            public void onStopPush() {
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.STOP_PUSH));
            }

            @Override
            public void onStartPlay(String url) {
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.START_PLAY, url));
            }

            @Override
            public void onStopPlay() {
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.STOP_PLAY));

            }

            @Override
            public void showActivity() {
                log("service : SHOW_ACTIVITY");
                ServiceManager.moveToFront();
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.SHOW_ACTIVITY));

                reconnectHandler.postDelayed(ServiceManager::moveToFront, 500);
            }

            @Override
            public void onUpdate(String url) {
                super.onUpdate(url);

                sendBrodcastToMain(new SimpleEvent(SimpleEvent.UPDATE, url));
            }

            @Override
            public void stopSelf() {
                log("service : stopSelf");
                SocketService.this.stopSelf();
            }

            @Override
            public void recaptureCamera() {
                super.recaptureCamera();
                sendBrodcastToMain(new SimpleEvent(SimpleEvent.RECAPTURE_CAMERA));
            }
        });
        simpleClient.start();
    }

    private void sendBrodcastToMain(SimpleEvent simpleEvent) {
        EventBus.getDefault().post(simpleEvent);
    }

    Handler reconnectHandler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (simpleClient == null) return;
            simpleClient.start();
        }
    };


    private void startReconnetct() {
        reconnectHandler.removeCallbacks(runnable);
        reconnectHandler.postDelayed(runnable, 5000);

        log("开始重连...");
        sendBrodcastToMain(new SimpleEvent(MainActivity.CODE_RECONNECTING));
    }


    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;

        if (simpleClient != null && simpleClient.isConnected()) {
            sendBrodcastToMain(new SimpleEvent(SimpleEvent.CONNECTED));
        }

        Notification notification;
        //进行8.0的判断
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            String CHANNEL_ONE_ID = "CHANNEL_ONE_ID";
            String CHANNEL_ONE_NAME = "CHANNEL_ONE_ID";
            NotificationChannel notificationChannel = null;
            notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                    CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setShowBadge(true);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(notificationChannel);

            notification = new Notification.Builder(this).setChannelId(CHANNEL_ONE_ID)
                    .setTicker("Nature")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("会议系统运行中")
                    .setContentText("会议系统运行中")
                    .build();
        } else {
            notification = new Notification.Builder(this)
                    .setTicker("Nature")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("会议系统运行中")
                    .setContentText("会议系统运行中")
                    .build();
        }
        notification.flags |= Notification.FLAG_NO_CLEAR;
        startForeground(1, notification);


        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        log("Service onDestroy");
        if (simpleClient != null) {
            simpleClient.stop();
            simpleClient = null;
        }
        super.onDestroy();
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    private void log(String s) {
        System.out.println("########   " + s);
    }


}
